package com.xjscrm.server.service.material.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.msg.MicaFriendTalkMsg;
import com.uzai.mobile.collect.api.enums.MicaTalkMsgType;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.msg.MsgData;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.common.util.MsgDataTools;
import com.xjscrm.server.dto.material.MaterialQuery;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.material.MaterialService;
import com.xjscrm.server.vo.device.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 素材管理
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class MaterialServiceImpl implements MaterialService {

    @Autowired
    private WwGroupMapper wwGroupMapper;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private MaterialConfigGroupMapper materialConfigGroupMapper;
    @Autowired
    private MaterialConfigMapper materialConfigMapper;
    @Autowired
    private MaterialMapper materialMapper;
    @Autowired
    private MaterialTagMapper materialTagMapper;
    @Autowired
    private MaterialTagRelationMapper materialTagRelationMapper;

    /**
     * 自动采集群内消息素材
     *
     * @param micaTransDto
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForQywxCallback")
    @TraceGenerate //注入消息id标签
    public void collectMaterialFromGroupMsg(MicaTransDto micaTransDto) {
        try {

            log.info("--监控系统日志--开始--");

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //查询该机器人的配置方案
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            //消息对象
            MicaFriendTalkMsg micaFriendTalkMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaFriendTalkMsg.class);
            if (micaFriendTalkMsg == null) {
                return;
            }

            //只处理群内消息
            if (!micaFriendTalkMsg.getGroup()) {
                return;
            }

            Integer msgType = micaFriendTalkMsg.getMsgType();
            if (msgType == null) {
                return;
            }

            if (msgType.intValue() != MicaTalkMsgType.Link.getCode().intValue()  //不等于连接
                    && msgType.intValue() != MicaTalkMsgType.WeApp.getCode().intValue() //不等于小程序
                    && msgType.intValue() != MicaTalkMsgType.ShiPinHao.getCode().intValue() //不等于视频号
            ) {
                return;
            }

            //发送者微信id
            String sendWxId = micaFriendTalkMsg.getSendWxId();
            //发送者微信昵称
            String sendNickName = micaFriendTalkMsg.getSendNickName();
            //查询该群消息
            String groupWxid = micaFriendTalkMsg.getConversationId();
            if (StringUtils.isBlank(sendWxId) || StringUtils.isBlank(groupWxid)) {
                return;
            }
            //获取群信息
            WwGroup wwGroup = wwGroupMapper.queryByDeviceUniqueIdAndGroupWxid(device.getId(), groupWxid);
            if (wwGroup == null) {
                return;
            }

            //判断群是否配置了自动采集素材
            MaterialConfigGroup materialConfigGroup = materialConfigGroupMapper.selectByDeviceIdAndGroupWxid(device.getDeviceId(), groupWxid, device.getMerId());
            if (materialConfigGroup == null) {
                return;
            }

            MaterialConfig materialConfig = materialConfigMapper.selectById(materialConfigGroup.getConfigId());
            if (materialConfig == null) {
                return;
            }

            //手机端采集是否启用(0-否;1-是）
            Integer mobileCollectStatus = Tools.getInteger(materialConfig.getMobileCollectStatus());
            if (mobileCollectStatus.intValue() != 1) {//未开启
                return;
            }

            List<MsgData> msgDataList = new ArrayList<>();
            MsgData msgData = MsgDataTools.getMsgData(micaFriendTalkMsg);
            if (msgData == null) {
                return;
            }
            msgDataList.add(msgData);

            //更新时间
            int now = DateUtil.getTime();
            //素材库类型（1-企业素材；2-个人素材）
            Integer type = Tools.getInteger(materialConfigGroup.getType());
            if (type.intValue() == 1) { //上传到企业素材
                //企业素材是否自动清理(0-否;1-是)
                Integer enterpriseClean = Tools.getInteger(materialConfig.getEnterpriseClean());
                //企业重要素材是否自动清理(0-否;1-是)
                Integer enterpriseImportantClean = Tools.getInteger(materialConfig.getEnterpriseImportantClean());
                MaterialQuery materialQuery = new MaterialQuery();
                materialQuery.setMerId(device.getMerId());
                //类型（1-企业素材；2-个人素材）
                materialQuery.setType(type);//企业素材
                materialQuery.setChildId(null); //企业素材不需要子账号id

                //如果不能清除重要素材，则查询条件设置只查询普通素材
                if (enterpriseImportantClean.intValue() == 1) {
                    materialQuery.setImportant(0);
                } else {//如果能清除重要素材，则能清除所有素材，故是否重要素材查询条件设置为null
                    materialQuery.setImportant(null);
                }
                //查询总数
                Integer count = Tools.getInteger(materialMapper.findCount(materialQuery));
                if (count.intValue() >= 2000) { //企业库最大只允许2000条
                    if (enterpriseClean.intValue() == 0) { //不开启自动清理
                        return;
                    } else {
                        //先清理在上传。一次性至少腾出10张位置
                        int deleteCount = count - 2000 + 10;
                        if (deleteCount < 10) {
                            deleteCount = 10;
                        }
                        //删除企业素材
                        materialMapper.deleteByEarliest(device.getMerId(), null, type, materialQuery.getImportant(), deleteCount);
                    }
                }

                Material mateial_enterprise = new Material();
                mateial_enterprise.setId(IdWorker.getId());
                mateial_enterprise.setMerId(device.getMerId());
                mateial_enterprise.setType(type);
                mateial_enterprise.setChildId(materialConfig.getChildId()); //企业素材不需要子账号id
                mateial_enterprise.setTitle("手机端收录素材");
                mateial_enterprise.setMsgType(micaFriendTalkMsg.getMsgType());
                mateial_enterprise.setMsgDatas(JSONObject.toJSONString(msgDataList));
                mateial_enterprise.setImportant(0);//不是重要素材
                mateial_enterprise.setUpdateUser(null);
                mateial_enterprise.setCreateTime(now);
                mateial_enterprise.setUpdateTime(now);
                materialMapper.insertSelective(mateial_enterprise);

                //素材标签
                List<Long> tagList = JSONObject.parseArray(materialConfigGroup.getTags(), Long.class);
                if (tagList != null && tagList.size() > 0) {
                    for (Long tagId : tagList) {
                        MaterialTag materialTag = materialTagMapper.selectById(tagId);
                        if (materialTag != null) {
                            MaterialTagRelation materialTagRelation = new MaterialTagRelation();
                            materialTagRelation.setId(IdWorker.getId());
                            materialTagRelation.setMerId(device.getMerId());
                            materialTagRelation.setMaterialId(mateial_enterprise.getId());
                            materialTagRelation.setTagId(tagId);
                            materialTagRelation.setCreateTime(now);
                            materialTagRelation.setUpdateTime(now);
                            materialTagRelationMapper.insertSelective(materialTagRelation);
                        }
                    }
                }

            } else if (type.intValue() == 2) { //上传到个人素材
                //个人素材是否自动清理(0-否;1-是)
                Integer privateClean = Tools.getInteger(materialConfig.getPrivateClean());
                //企业重要素材是否自动清理(0-否;1-是)
                Integer privateImportantClean = Tools.getInteger(materialConfig.getPrivateImportantClean());
                MaterialQuery materialQuery = new MaterialQuery();
                materialQuery.setMerId(device.getMerId());
                //类型（1-企业素材；2-个人素材）
                materialQuery.setType(type);//个人素材
                materialQuery.setChildId(materialConfig.getChildId());
                //如果不能清除重要素材，则查询条件设置只查询普通素材
                if (privateImportantClean.intValue() == 1) {
                    materialQuery.setImportant(0);
                } else {//如果能清除重要素材，则能清除所有素材，故是否重要素材查询条件设置为null
                    materialQuery.setImportant(null);
                }
                //查询总数
                Integer count = Tools.getInteger(materialMapper.findCount(materialQuery));
                if (count.intValue() >= 1000) { //个人库最大只允许1000条
                    if (privateClean.intValue() == 0) { //不开启个人素材自动清理
                        return;
                    } else {
                        //先清理在上传。一次性至少腾出10张位置
                        int deleteCount = count - 1000 + 10;
                        if (deleteCount < 10) {
                            deleteCount = 10;
                        }
                        //删除个人素材
                        materialMapper.deleteByEarliest(device.getMerId(), materialConfig.getChildId(), type, materialQuery.getImportant(), deleteCount);
                    }
                }

                Material mateial_private = new Material();
                mateial_private.setId(IdWorker.getId());
                mateial_private.setMerId(device.getMerId());
                mateial_private.setType(type);
                mateial_private.setChildId(materialConfig.getChildId());
                mateial_private.setTitle("手机端收录素材");
                mateial_private.setMsgType(micaFriendTalkMsg.getMsgType());
                mateial_private.setMsgDatas(JSONObject.toJSONString(msgDataList));
                mateial_private.setImportant(0);//不是重要素材
                mateial_private.setUpdateUser(null);
                mateial_private.setCreateTime(now);
                mateial_private.setUpdateTime(now);
                materialMapper.insertSelective(mateial_private);

                //素材标签
                List<Long> tagList = JSONObject.parseArray(materialConfigGroup.getTags(), Long.class);
                if (tagList != null && tagList.size() > 0) {
                    for (Long tagId : tagList) {
                        MaterialTag materialTag = materialTagMapper.selectById(tagId);
                        if (materialTag != null) {
                            MaterialTagRelation materialTagRelation = new MaterialTagRelation();
                            materialTagRelation.setId(IdWorker.getId());
                            materialTagRelation.setMerId(device.getMerId());
                            materialTagRelation.setMaterialId(mateial_private.getId());
                            materialTagRelation.setTagId(tagId);
                            materialTagRelation.setCreateTime(now);
                            materialTagRelation.setUpdateTime(now);
                            materialTagRelationMapper.insertSelective(materialTagRelation);
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }finally {
            log.info("--监控系统日志--结束--");
        }
    }

}
